var videos;
var videoIndex;
function showstatus(){
	$("flashcontent").innerHTML = "";
	$("flashcontent").setStyle("display", "none");
	$("log").setStyle("display", "block");
}
function updatestatus(str){
	//$("flashcontent").setStyle("display", "none");
	//$("log").setStyle("display", "block");
	$("log").innerHTML = str;
}
function setAudioTime(time){
	//so.setProxy('youtubevid', SWF_PATH+'swfobject_js_gateway.swf');
	//var at = so.call('setAudioTime', time);
	//return (new Date().getTime());
	//$('youtubevid').setAudioTime(time);
}
function setAudioTime2(time){
/*	//so.setProxy('youtubevid', SWF_PATH+'swfobject_js_gateway.swf');*/
	var at = so.call('setAudioTime2', time);
	return (new Date().getTime());
}
function startVideo(){
	alert(videoIndex+ " : "+videos.length);
	playVideo(videos[videoIndex].id, videos[videoIndex].title);
}
function skipForward(){
	var lastIndex = videos.length -1;
	if(videoIndex < lastIndex){
		videoIndex++;	
		startVideo();		
	}
	if(videoIndex == lastIndex)
		$("bt-forward").className = "last";
	else
		$("bt-forward").className = "";
}
function playVideo(video_id, title){

	var tube_url = YOUTUBE_PATH+"watch?v="+video_id;
	updatestatus("Getting fullscreen video.");
	/*try {
		netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	} catch (e) {
		alert("Permission UniversalBrowserRead denied.");
	}*/
	var myAjax = new Ajax(PROXY_URL ? PROXY_URL : tube_url, {
		method: PROXY_URL ? 'POST' : 'GET',
		data: {"url":tube_url},
		onComplete: function(responseText, responseXML){
			updatestatus("Video found");
	/* when youtube changes update this regex */
	/*
			var fullscreenUrl = '/watch_fullscreen?fs=1&vq=None&hl=en&ad_module=http%3A%2F%2Fs.ytimg.com%2Fyt%2Fswf%2Fad-vfl51923.swf&video_id=r-ADQg8Qcis&l=243&fmt_map=&sk=1PyfL0UvvPMb7-S41AdgAsgRP4HsGaL5C&invideo=True&t=OEgsToPDskK084eaPIPxNgRdWW330-R0&plid=AARVEGy5SlQ_kVdVAAAAyBDiAAg&tk=SdnD7bmJetHmkgHzhCsGlMP5r0RKLJKxiH1anmCTroOodxKLRyJvqQ%3D%3D&title=Nelly Furtado - Say It Right';
					var fullscreenUrl = '/watch_fullscreen?fs=1&vq=None&video_id=J7_M7CAbrlc&l=229&sk=1PyfL0UvvPMb7-S41AdgAsgRP4HsGaL5C&fmt_map=&t=OEgsToPDskLldXSTHjsWQlrkEekDvj0E&hl=en&plid=AARVEHMrGH9Ur_YcAAAAoABsYAE&tk=SdnD7bmJetHmkgHzhCsGlL0jrB_31JzsgynNrf9ygTpdm3eq_c81LQ%3D%3D&title=Say it Right by Nelly Furtado, Sims Style';
					
			*/
			//alert(tube_url);
			
			var string = responseText.match(/watch_fullscreen\?fs=1&(.+)\'/i); /* ' */
			string = string[1].match(/video_id\=(.+)&/i);
			
			try{
				var fullscreenurl = YOUTUBE_PATH+"player2.swf?v=1&video_id="+string[1];
				alert("furl "+fullscreenurl);
				//embedSWF(fullscreenurl);
				embedTubePlayer(fullscreenurl);
				updateTitle(title, tube_url);
			}catch(e){
				alert("youtube video error"+e);
				updateTitle("Error: could not find fullscreen url.", tube_url);
			}
			
		}
	}).request();
}
function embedSWF(url){
	updatestatus("Playing video.");
	var so = new SWFObject(url, "youtubevid", "100%", "100%", "8");
	so.addParam("allowFullScreen", "true");
	so.addParam("allowScriptAccess", "always");
	so.write("flashcontent");
	$("flashcontent").setStyle("display", "block");
	$("log").setStyle("display", "none");
}


function embedTubePlayer(fullscreenurl){
alert("starting embed");
	//fullscreenurl = 'http://www.youtube.com/player2.swf?v=1&video_id=BSYQcFi_ayY&l=384&t=OEgsToPDskKqMyYKZe0YhsTfINkkxu1q&sk=5j8b8XW5UKH3ReeFBfKJ9AC&fs=1&title="We Will Become Silhouettes" by the Postal Service';
	var matches = fullscreenurl.match(/video_id=(.+?)&/i);	
	video_id = matches[1];
	try{
		var matches = fullscreenurl.match(/t=(.+?)&/i);	
		t = matches[1];
	}catch(e){
		alert("Error: could not find fullscreen url."+ fullscreenurl);
		updateTitle("Error: could not find fullscreen url.", fullscreenurl);
		t = null;
	}
//	var matches = fullscreenurl.match(/sk=(.+?)&/i);	
//	sk = matches[1];

	so = new SWFObject(SWF_PATH+SWF_PLAYER, "youtubevid", "100%", "100%", "8");
	so.addVariable( 'video_id', video_id );
	so.addVariable( 't', t );
//	so.addVariable( 'code', sk );
	so.addVariable( 'set_volume', VOLUME );
	if(TRY_SYNC){
		alert("seek to "+trackinfo.time ); // dont use the stored currentsong data
		so.addVariable( 'seek_to_sec', (trackinfo.time + 2) );
	}else{
		so.addVariable( 'seek_to_sec', -1 );
	}
	so.addVariable( 'audio_totaltime', (currentsong.totaltime) );
	so.addVariable( 'video_smoothing', "true" );
	so.addParam("allowScriptAccess", "always");
	//so.addVariable( 'seek_to', "50" );
	//trace(t);
	//trace(t);
	//trace(sk);
	so.write("flashcontent");

	
	
	
	$("flashcontent").setStyle("display", "block");
	$("log").setStyle("display", "none");
	
	attachControls();
	//document.youtubevid.SetVariable("_root:seek_to_sec", 50);
}


function searchCompleted(HTML){
	videos = new Array();

	if(!HTML) return;

	var videoMatches = HTML.match(/vEntry([^`]*?)end\s*vEntry/mgi);
	if(!videoMatches) videoMatches = HTML.match(/vEntry([^`]*?)\<\/td\>/mgi);

	var pattern1 = new RegExp("\"errorBox\"", "i"); 
	var notFound = HTML.match(pattern1) || HTML.match(/user\s*doesn't\s*have\s*any/i); /* '  */
	if(!videoMatches || notFound)
	{
		//renderVideoGuide(null, showGuide, header, subheader);
		//return;
	}

	if(HTML.match(/class=\"pager[^>]*\>\s*Next\s*<\/a\>/i)) /* "  */
	{
		var currPage = HTML.match(/class=\"pagerCurr[^>]*\>\s*(\d+)/i); /* "  */
		if(currPage) nextPage = 1*(currPage[1]) + 1;

	} else nextPage = -1;

	if(! videoMatches){
		updatestatus("No video found on youtube.");
		return;
	}
	
	for(var i = 0; i < videoMatches.length; i++)
	{
		var videoHTML = videoMatches[i];
		var video = new Object();

		//if(i == 0) alert(videoHTML);

		video.id = parseListID(videoHTML);
		video.title = parseListTitle(videoHTML);
		/*video.length = parseListLength(videoHTML);
		video.imageURL = parseListImageURL(videoHTML, video.id);
		video.rating = parseListRating(videoHTML);
		video.ratings = parseListRatings(videoHTML);
		video.views = parseListViews(videoHTML);*/
		video.date = parseListDate(videoHTML);
		//video.user = parseListUser(videoHTML);

		var theMatch;

		theMatch = videoHTML.match(/Added:[^>]*\>(.*)/mi);
		video.date = (theMatch) ? theMatch[1] : "";

		theMatch = video.date.match(/\((\d+)\)/);

		//this could be better...
		if(theMatch)
		{
			var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
			var date = new Date(theMatch[1]);
			date.setHours(date.getHours() + date.getTimezoneOffset()/60);
			video.date = months[date.getMonth()] + " " + date.getDate() + ", " + date.getFullYear();
		}

		videos.push(video);
	}
	videoIndex = 0;
	startVideo();


}
function parseListID(HTML)
{
	var id = HTML.match(/watch\?v=([^"]+)/i);  /* "  */
	return (id) ? id[1] : "";
}
function parseListTitle(HTML)
{
	var title = HTML.match(/watch\?v=[^>]*\>(([^<]|\<[^i]).*?[^/].)\<\/a/i);
	return (title) ? title[1] : "Untitled Video";
}
function parseListDate(HTML)
{
	var date = HTML.match(/Added:[^>]*\>(.*)/mi);
	date = (date) ? date[1] : "";

	date = date.match(/\((\d+)\)/);

	//this could be better...
	if(date)
	{
		var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
		var dateObj = new Date(date[1]);
		dateObj.setHours(dateObj.getHours() + dateObj.getTimezoneOffset()/60);
		return months[dateObj.getMonth()] + " " + dateObj.getDate() + ", " + dateObj.getFullYear();
	}
	return "-";
}